package com.louis.buddhist.ui.activity;

import android.content.Intent;
import android.graphics.Point;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.dyhdyh.widget.loading.dialog.LoadingDialog;
import com.louis.buddhist.R;
import com.louis.buddhist.data.C;
import com.louis.buddhist.data.entity.Book;
import com.louis.buddhist.data.entity.CatalogEntity;
import com.louis.buddhist.data.entity.CollectEntity;
import com.louis.buddhist.data.entity.Page;
import com.louis.buddhist.data.entity.PageEntity;
import com.louis.buddhist.data.entity.Read;
import com.louis.buddhist.data.entity.ReadAllEntity;
import com.louis.buddhist.data.http.HttpManager;
import com.louis.buddhist.db.BookDaoOpen;
import com.louis.buddhist.db.CollectDaoOpen;
import com.louis.buddhist.db.ReadDaoOpen;
import com.louis.buddhist.interfaces.ReadCloseActivityListener;
import com.louis.buddhist.ui.adapter.ReadPreviewAdapter;
import com.louis.buddhist.ui.base.BaseActivity;
import com.louis.buddhist.util.CommonUtil;
import com.louis.buddhist.widget.dialog.CatalogDialogFragment;
import com.louis.buddhist.widget.dialog.CollectDialogFragment;
import com.louis.buddhist.widget.dialog.ReadDialogFragment;
import com.louis.buddhist.widget.view.PageFactory;
import com.louis.buddhist.widget.view.PageWidget;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import io.reactivex.functions.BiFunction;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class ReadActivity extends BaseActivity implements View.OnClickListener, CatalogDialogFragment.PageToCatalogListener, ReadCloseActivityListener {

    @BindView(R.id.bookpage)
    PageWidget mBookPage;
    @BindView(R.id.ll_main_page)
    LinearLayout mLLMainPage;
    @BindView(R.id.ll_preview)
    LinearLayout mLLPreview;
    @BindView(R.id.rv_list)
    RecyclerView mRecyclerView;
    @BindView(R.id.ll_catalog)
    LinearLayout mLLCatalog;
    @BindView(R.id.iv_collect)
    ImageView mIvCollect;
    @BindView(R.id.drawerlayout)
    DrawerLayout mDrawerLayout;
    @BindView(R.id.toolbar)
    Toolbar mToolbar;
    @BindView(R.id.iv_setting)
    ImageView mIvSetting;
    @BindView(R.id.tv_main_page)
    TextView mTvMainPage;
    @BindView(R.id.tv_constacts_us)
    TextView mTvConstactsUs;
    @BindView(R.id.tv_disclaimer)
    TextView mTvDisclaimer;
    @BindView(R.id.tv_collect)
    TextView mTvCollect;
    @BindView(R.id.tv_read)
    TextView mTvRead;
    @BindView(R.id.tv_version)
    TextView mTvVersion;

    //
    private PageFactory pageFactory;
    private List<File> mFileList;
    private List<Page> mPageList = new ArrayList<>();
    private int screenWidth, screenHeight;
    private ReadPreviewAdapter mAdapter;
    private boolean isPreviewShow = false;
    private Disposable mDisposable;
    private ArrayList<CatalogEntity.EbookContentBean> mCatalogList;
    private Book mBook;
    private int mPage;
    private String mContentId;
    private List<CollectEntity> mCollectList;

    @Override
    protected int setContentView() {
        return R.layout.activity_read;
    }

    @Override
    protected void initView() {
        Intent intent = getIntent();
        if (intent != null) {
            mBook = intent.getParcelableExtra(C.IntentKey.MESSAGE_INTENT_KEY);
            mPage = intent.getIntExtra(C.IntentKey.MESSAGE_INTENT_KEY2, 0);
            String path = mBook.getPath();
            mContentId = mBook.getContentId();
            File file = new File(path);
            File[] files = file.listFiles();

            if (files == null || files.length == 0) {
                BookDaoOpen.deleteData(this, mBook);
                Toast.makeText(ReadActivity.this, "書在手機上已不存在，請重新下載！", Toast.LENGTH_SHORT).show();
                finish();
            }

            mFileList = Arrays.asList(files);
        }

        setSupportActionBar(mToolbar);
        //隐藏toolbar上的title
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        ActionBarDrawerToggle drawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, mToolbar, R.string.drawer_open, R.string.drawer_close);
        //同步状态
        drawerToggle.syncState();
        //给侧滑控件设置监听
        mDrawerLayout.addDrawerListener(drawerToggle);
        mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);

        mCollectList = CollectDaoOpen.queryByName(this, mBook.getName());

        initRecyclerView();
        mTvVersion.setText("版本號：" + CommonUtil.getVersion(this));
    }

    private void initRecyclerView() {
        mAdapter = new ReadPreviewAdapter(R.layout.adapter_read_preview, mPageList);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, OrientationHelper.HORIZONTAL, false);

        mRecyclerView.setLayoutManager(linearLayoutManager);
        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {

            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                pageFactory.setCurrentPage(position);
                pageFactory.currentPage(true);
            }
        });
        mRecyclerView.setAdapter(mAdapter);
    }

    @Override
    protected void initData() {
        mLLMainPage.setOnClickListener(this);
        mLLPreview.setOnClickListener(this);
        mLLCatalog.setOnClickListener(this);
        mIvCollect.setOnClickListener(this);
        mIvSetting.setOnClickListener(this);
        mTvMainPage.setOnClickListener(this);
        mTvConstactsUs.setOnClickListener(this);
        mTvDisclaimer.setOnClickListener(this);
        mTvCollect.setOnClickListener(this);
        mTvRead.setOnClickListener(this);

        getData();
    }

    private void init() {
        if (Build.VERSION.SDK_INT >= 14 && Build.VERSION.SDK_INT < 19) {
            mBookPage.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        }

        pageFactory = PageFactory.getInstance();
        //获取屏幕宽高
        WindowManager manage = getWindowManager();
        Display display = manage.getDefaultDisplay();
        Point displaysize = new Point();
        display.getSize(displaysize);
        screenWidth = displaysize.x;
        screenHeight = displaysize.y;
        //保持屏幕常亮
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        pageFactory.setPageWidget(mBookPage);
        try {
            pageFactory.openBook(mList, mPage);
        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(this, "打开电子书失败", Toast.LENGTH_SHORT).show();
        }
    }

    private void initListener() {

        mBookPage.setTouchListener(new PageWidget.TouchListener() {
            @Override
            public void center() {

            }

            @Override
            public Boolean prePage() {

                //                pageFactory.prePage();
                //                if (pageFactory.isfirstPage()) {
                //                    return false;
                //                }

                pageFactory.nextPage();
                if (pageFactory.islastPage()) {
                    return false;
                }

                isCheck();

                return true;
            }

            @Override
            public Boolean nextPage() {
                //                Log.e("setTouchListener", "nextPage");

                //                pageFactory.nextPage();
                //                if (pageFactory.islastPage()) {
                //                    return false;
                //                }
                //                return true;

                pageFactory.prePage();
                if (pageFactory.isfirstPage()) {
                    return false;
                }

                isCheck();


                return true;
            }

            @Override
            public void cancel() {
                pageFactory.cancelPage();
            }
        });
    }

    private void isCheck() {
        if(mCollectList != null && mCollectList.size() > 0) {
            boolean b = true;
            for (CollectEntity collectEntity : mCollectList) {
                if (pageFactory.getCurrentPage() + 1 == collectEntity.getPage()){
                    mIvCollect.setImageResource(R.drawable.icon_collected);
                    b = false;
                    break;
                }
            }
            if(b) {
                mIvCollect.setImageResource(R.drawable.icon_collect);
            }
        }
    }

    @Override
    protected void onDestroy() {


        Read read = ReadDaoOpen.queryByName(this, mBook.getName());
        int currentPage = pageFactory.getCurrentPage() + 1;
        Read entity = new Read();
        if (read != null) {
            entity.setId(read.getId());
        }
        entity.setName(mBook.getName());
        entity.setPage(currentPage);
        entity.setDate(new Date());
        entity.setCover(mBook.getCover());
        ReadDaoOpen.saveData(this, entity);

        super.onDestroy();
        pageFactory.clear();
        mBookPage = null;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_main_page:
            case R.id.tv_main_page:
                finish();
                break;
            case R.id.ll_preview:
                if (isPreviewShow) {
                    mRecyclerView.setVisibility(View.GONE);
                    isPreviewShow = false;
                } else {
                    mRecyclerView.setVisibility(View.VISIBLE);
                    isPreviewShow = true;
                }
                break;
            case R.id.ll_catalog:
                showCatalog();
                break;
            case R.id.iv_collect:
                collect();
                break;
            case R.id.iv_setting:
                mDrawerLayout.openDrawer(Gravity.LEFT);
                break;
            case R.id.tv_constacts_us:
                toContacts();
                break;
            case R.id.tv_disclaimer:
                toDisclaimer();
                break;
            case R.id.tv_collect:
                showCollectList();
                break;
            case R.id.tv_read:
                showReadList();
                break;
        }
    }

    private void toContacts() {
        Intent intent = new Intent(this, ContactsUsActivity.class);
        startActivity(intent);
        finish();
    }

    private void toDisclaimer() {
        Intent intent = new Intent(this, DisclaimerActivity.class);
        startActivity(intent);
        finish();
    }

    private void showCollectList() {
        CollectDialogFragment fragment = new CollectDialogFragment();
        fragment.setmListener(this);
        fragment.show(getSupportFragmentManager(), "CollectDialogFragment");
        mDrawerLayout.closeDrawer(Gravity.LEFT);
    }

    private void showReadList() {
        ReadDialogFragment fragment = new ReadDialogFragment();
        fragment.setmListener(this);
        fragment.show(getSupportFragmentManager(), "ReadDialogFragment");
        mDrawerLayout.closeDrawer(Gravity.LEFT);
    }

    private void collect() {
        int currentPage = pageFactory.getCurrentPage() + 1;

        CollectEntity collectEntity = CollectDaoOpen.queryByNameAndPage(this, mBook.getName(), currentPage);
        if (collectEntity == null) {
            CollectEntity entity = new CollectEntity();
            entity.setName(mBook.getName());
            entity.setPage(currentPage);
            entity.setDate(new Date());
            entity.setCover(mList.get(currentPage - 1).getAbsolutePath());
            CollectDaoOpen.insertData(this, entity);
        } else {
            //collectEntity.setPage(currentPage);
            //collectEntity.setDate(new Date());
            //CollectDaoOpen.insertData(this, collectEntity);
        }
        mIvCollect.setImageResource(R.drawable.icon_collected);
    }

    private void showCatalog() {
        if (mCatalogList != null && mCatalogList.size() > 0) {
            CatalogDialogFragment fragment = new CatalogDialogFragment();
            fragment.setmListener(this);
            Bundle bundle = new Bundle();
            bundle.putParcelableArrayList(C.IntentKey.MESSAGE_INTENT_KEY, mCatalogList);
            fragment.setArguments(bundle);
            fragment.show(getSupportFragmentManager(), "CatalogDialogFragment");
        } else {
            Toast.makeText(this, mBook.getName() + "沒有目錄！", Toast.LENGTH_SHORT).show();
        }
    }

    private void getData() {

        Observable.combineLatest(HttpManager.getApiInstance().getBookPaging(mContentId), HttpManager.getApiInstance().getBookCatalog(mContentId), new BiFunction<PageEntity, CatalogEntity, ReadAllEntity>() {
            @Override
            public ReadAllEntity apply(PageEntity pageEntity, CatalogEntity catalogEntity) throws Exception {
                return new ReadAllEntity(pageEntity, catalogEntity);
            }
        })
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        LoadingDialog.make(ReadActivity.this).show();
                    }
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doFinally(new Action() {
                    @Override
                    public void run() throws Exception {
                        LoadingDialog.cancel();
                    }
                })
                .subscribe(new Observer<ReadAllEntity>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        mDisposable = d;
                    }

                    @Override
                    public void onNext(ReadAllEntity entity) {
                        CatalogEntity catalogEntity = entity.getCatalogEntity();
                        mCatalogList = (ArrayList<CatalogEntity.EbookContentBean>) catalogEntity.getEbook_content();

                        PageEntity pageEntity = entity.getPageEntity();
                        if (pageEntity.getRet() == 100) {
                            initPage(pageEntity.getContainer());
                        } else {
                            Toast.makeText(ReadActivity.this, pageEntity.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        System.out.println(e);
                    }

                    @Override
                    public void onComplete() {
                        System.out.println("onComplete");
                    }
                });
    }

    private List<File> mList = new ArrayList<>();


    private void initPage(LinkedHashMap<String, String> map) {
        //        for (File file : mFileList) {
        //            String page = map.get(file.getName());
        //            if(TextUtils.isEmpty(page)){
        //                mPageList.add(new Page(file, file.getName()));
        //            }else {
        //                mPageList.add(new Page(file, page));
        //            }
        //        }

        Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();

        while (iterator.hasNext()) {
            Map.Entry<String, String> entry = iterator.next();
            for (File file : mFileList) {
                if (file.getName().equals(entry.getKey())) {
                    String page = entry.getValue();
                    if (TextUtils.isEmpty(page)) {
                        mPageList.add(new Page(file, file.getName()));
                    } else {
                        mPageList.add(new Page(file, page));
                    }
                    mList.add(file);
                }
            }
        }
        init();
        initListener();
    }

    public void getCatalog() {
        HttpManager.getApiInstance().getBookCatalog(mContentId)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        LoadingDialog.make(ReadActivity.this).show();
                    }
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doFinally(new Action() {
                    @Override
                    public void run() throws Exception {
                        LoadingDialog.cancel();
                    }
                })
                .subscribe(new Observer<CatalogEntity>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        mDisposable = d;
                    }

                    @Override
                    public void onNext(CatalogEntity entity) {
                        mCatalogList = (ArrayList<CatalogEntity.EbookContentBean>) entity.getEbook_content();
                    }

                    @Override
                    public void onError(Throwable e) {
                        System.out.println(e);
                    }

                    @Override
                    public void onComplete() {
                        System.out.println("onComplete");
                    }
                });
    }

    @Override
    public void toPage(CatalogEntity.EbookContentBean bean) {
        int page = bean.getPage_no();
        pageFactory.setCurrentPage(page);
        pageFactory.currentPage(true);
    }

    @Override
    public void close() {
        finish();
    }
}
